package com.lx.wrapper.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.lx.constant.consts.SqlFormatConstant;
import com.lx.constant.consts.SqlKeyWordConstant;
import com.lx.constant.enums.SegmentEnum;
import com.lx.constant.segment.Segment;
import com.lx.wrapper.AbstractMainEntityLambdaConditionWrapper;
import com.lx.wrapper.AbstractWrapper;
import org.hibernate.query.Query;

import java.util.List;
import java.util.Map;

/**
 * Lambda删除语句对象
 *
 * @author lx
 * @create 2023/1/31 18:05
 **/
public class LambdaDeleteWrapper<MainEntity> extends AbstractMainEntityLambdaConditionWrapper<MainEntity, LambdaDeleteWrapper<MainEntity>> {

    public LambdaDeleteWrapper() {
        this(null);
    }

    public LambdaDeleteWrapper(Class<MainEntity> entityClass) {
        super(entityClass);
    }


    @Override
    protected void setHibernateParamByQuery0(boolean isHQL, Query query) {
        //其他映射
        Map<SegmentEnum, List<Segment>> segmentsMap = getSegmentsByEnums(SegmentEnum.WHERE, SegmentEnum.LIMIT);
        segmentsMap.forEach((e1, l1) -> {
            if (CollectionUtil.isEmpty(l1)) {
                return;
            }
            for (Segment sn : l1) {
                sn.setHibernateParamByQuery(isHQL, query);
            }
        });
    }

    @Override
    protected String getCompleteQL0(boolean isHQL, AbstractWrapper parentWrapper) {
        //根据条件构建更新SQL
        StringBuilder sqlBuilder = new StringBuilder(512);
        //1.组建 delete from 表名 语句
        sqlBuilder.append(SqlKeyWordConstant.DELETE);
        String tableAliasName = getTableAliasName(false);
        if (!isHQL) {
            //sql语法的delete不支持别名删除,需要做一层中转. 语法如下: DELETE alias FROM Entity AS alias
            sqlBuilder.append(tableAliasName);
        }
        sqlBuilder.append(SqlKeyWordConstant.FROM).append(String.format(SqlFormatConstant.AS_FORMAT, inferAndGetTableName(isHQL), tableAliasName));
        //2.构建条件项.
        sqlBuilder.append(buildConditions(isHQL, parentWrapper, SegmentEnum.WHERE));
        //3.构建分页条件
        sqlBuilder.append(buildConditions(isHQL, parentWrapper, SegmentEnum.LIMIT));
        return sqlBuilder.toString();
    }

}
